package com.czk.springcloud.snowflake;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 糊涂工具类的雪花算法
 *
 * @Author:ChenZhangKun
 * @Date: 2020/12/27 21:41
 */
@Slf4j
@Component
public class IdGeneratorSnowflake {
    /**
     * 工作机房id
     */
    private Long workerId = 0L;
    /**
     * 机房设备id
     */
    private Long dataCenterId = 1L;
    private Snowflake snowflake = IdUtil.createSnowflake(workerId, dataCenterId);

    @PostConstruct
    public void init() {
        try {
            // 本机的编码
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
            log.info("得到当前机器的workId:{}", workerId);
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("当前机器的workId获取失败", ex);
            workerId = Long.parseLong(NetUtil.getLocalhostStr().hashCode() + "");
        }

    }

    /**
     * 获取雪花id
     *
     * @return
     */
    public synchronized Long snowflakeId() {
        return snowflake.nextId();
    }

    public synchronized Long snowflakeId(Long workerId, Long dataCenterId) {
        return IdUtil.createSnowflake(workerId, dataCenterId).nextId();
    }

    public static void main(String[] args) {
        System.out.println(new IdGeneratorSnowflake().snowflakeId());
    }
}
